﻿using LitJson;
using System.Collections.Generic;

namespace CGF
{
    public static class SignHelper
    {
        /// <summary>
        /// 给Json数据签名（转成"a=1&c=3&b=2"的形式后按Ascii码排序后拼接key或取MD5）
        /// </summary>
        public static string SignJson(JsonData jsonData, string key, bool includeEmptyParam = false)
        {
            if (jsonData == null) return "";
            List<string> list = new List<string>();
            foreach (var k in jsonData.Keys)
            {
                list.Add($"{k}={jsonData[k]}");
            }
            list.Sort();
            string content = "";
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Trim().StartsWith("sign=")) continue;
                if (!includeEmptyParam)
                {
                    string[] arr2 = list[i].Split('=');
                    if (arr2[1].Trim() == "") continue;
                }
                if (!string.IsNullOrEmpty(content)) content += "&";
                content += list[i];
            }
            return MD5Helper.StringToMD5($"{content}&key={key}");
        }

        /// <summary>
        /// 给数据签名（传入"a=1&c=3&b=2"数据会自动按Ascii码排序后拼接key或取MD5）
        /// </summary>
        public static string SignParams(string urlParams, string key, bool includeEmptyParam = false)
        {
            if (string.IsNullOrEmpty(urlParams)) return "";
            if (!urlParams.Contains("&"))
            {
                return MD5Helper.StringToMD5($"{urlParams}&key={key}");
            }
            string[] arr = urlParams.Split('&');
            List<string> list = new List<string>(arr);
            list.Sort();
            string content = "";
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Trim().StartsWith("sign=")) continue;
                if (!includeEmptyParam)
                {
                    string[] arr2 = list[i].Split('=');
                    if (arr2[1].Trim() == "") continue;
                }
                if (!string.IsNullOrEmpty(content)) content += "&";
                content += list[i];
            }
            return MD5Helper.StringToMD5($"{content}&key={key}");
        }

        /// <summary>
        /// 给数据签名（传入"a=1&c=3&b=2"数据会自动按Ascii码排序后拼接key或取MD5）
        /// </summary>
        public static string SignDictionary(Dictionary<string, object> dictionary, string key, bool includeEmptyParam = false)
        {
            List<string> list = new List<string>(dictionary.Keys);
            list.Sort();
            string content = "";
            for (int i = 0; i < list.Count; i++)
            {
                string dicKey = list[i];
                if (dicKey == "sign") continue;
                if (!includeEmptyParam)
                {
                    if (dictionary[dicKey].ToString() == "") continue;
                }
                if (!string.IsNullOrEmpty(content)) content += "&";
                content += $"{dicKey}={dictionary[dicKey]}";
            }
            return MD5Helper.StringToMD5($"{content}&key={key}");
        }
        
        /// <summary>
        /// 给Json验签
        /// </summary>
        public static bool VerifyJson(JsonData jsonData, string secret,  bool includeEmptyParam = false)
        {
            if (jsonData == null) return false;
            List<string> list = new List<string>();
            foreach (var k in jsonData.Keys)
            {
                list.Add($"{k}={jsonData[k]}");
            }
            list.Sort();
            string content = "";
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Trim().StartsWith("sign=")) continue;
                if (!includeEmptyParam)
                {
                    string[] arr2 = list[i].Split('=');
                    if (arr2[1].Trim() == "") continue;
                }
                if (!string.IsNullOrEmpty(content)) content += "&";
                content += list[i];
            }
            return MD5Helper.StringToMD5($"{content}&key={secret}") == jsonData["sign"].ToString();
        }

        /// <summary>
        /// 打印签名细节
        /// </summary>
        public static string Detail(Dictionary<string, object> dictionary, string key, bool includeEmptyParam = false)
        {
            List<string> list = new List<string>(dictionary.Keys);
            list.Sort();
            string content = "";
            for (int i = 0; i < list.Count; i++)
            {
                string dicKey = list[i];
                if (dicKey == "sign") continue;
                if (!includeEmptyParam)
                {
                    if (dictionary[dicKey].ToString() == "") continue;
                }
                if (!string.IsNullOrEmpty(content)) content += "&";
                content += $"{dicKey}={dictionary[dicKey]}";
            }
            return $"{content}&key={key}";
        }
    }
}